package com.mytravel

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.android.architecture.helper.Logger
import com.mytravel.MyApp.Companion.TAG

/**
 * Created by SuQi on 2024/9/26.
 * Describe:
 */
class UploadService : Service() {

    override fun onCreate() {
        Logger.i(TAG, "onCreate")
        super.onCreate()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Logger.i(TAG, "onStartCommand")
        startForeground()
        UploadHelper.uploadAddressInfo()
//        return super.onStartCommand(intent, flags, startId)
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        Logger.i(TAG, "onBind")
        return null
    }

    override fun onUnbind(intent: Intent?): Boolean {
        Logger.i(TAG, "onUnbind")
        return super.onUnbind(intent)
    }

    override fun onDestroy() {
        Logger.i(TAG, "onDestroy")
        stopForeground()
        super.onDestroy()
    }

    @SuppressLint("ForegroundServiceType")
    private fun startForeground() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            startForeground(1, createNotification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST)
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForeground(1, createNotification())
        }
    }

    private fun stopForeground() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            stopForeground(true)
        }
    }

    private fun createNotification(): Notification {
        val channelId = TAG
        val builder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentText("$TAG is running")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(false)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel(channelId, TAG, NotificationManager.IMPORTANCE_HIGH)
            channel.description = "$TAG Is Running"
            val notificationManager = getSystemService(
                NotificationManager::class.java
            )
            notificationManager.createNotificationChannel(channel)
        }
        return builder.build()
    }


}